package com.leyou.cart.interceptor;

import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.cart.config.JwtProperties;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * *
 * Created by IntelliJ IDEA.
 * Author: caoLei
 * Date: 2018/11/6
 * Time: 21:10
 * *
 */
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties jwtProperties;

    //定义一个线程域，用来存放登录用户,这里我们使用了ThreadLocal来存储查询到的用户信息，线程内共享，因此请求到达Controller后可以共享User
    @Autowired
    private static final ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从cookie中获取jwt类型的token
        String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
        //判断token是否为null
        if (StringUtils.isBlank(token)) {
            //重定向到登录界面
            response.sendRedirect("http://www.leyou.com/login.html?returnUrl=http://www.leyou.com/cart.html");
            return false;
        }
        //有token，查询用户信息
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
        //判断userinfo是否为空
        if (userInfo == null) {
            //重定向到登录页面
            response.sendRedirect("http://www.leyou.com/login.html?returnUrl=http://www.leyou.com/cart.html");
            return false;
        }
        //userInfo不为空，表名解析成功
        //将userInfo放入线程域中
        threadLocal.set(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //必须清除线程变量，因为我们使用的是tomcat线程池，一个请求处理完成之后，并没与销毁线程，而是把该线程还回到线程池中，等待下一次的调用
        threadLocal.remove();
    }

    //由于我们的threadlocal定义的是private static final，这样后面的controller等就获得不了threadlocal

    //定义一个静态方法用来获取user信息
    public static UserInfo get() {
        return threadLocal.get();
    }
}
